@using Elsa.Studio.Models
@using Elsa.Api.Client.Shared.UIHints.SingleLine
@using Elsa.Studio.DomInterop.Contracts
@using Elsa.Studio.UIHints.Extensions
@inject ILocalizer Localizer

@{
    var inputDescriptor = EditorContext.InputDescriptor;
    var displayName = inputDescriptor.DisplayName;
    var description = inputDescriptor.Description;
    var inputValue = EditorContext.GetLiteralValueOrDefault();
    var adornment = !string.IsNullOrWhiteSpace(_singleLineProps.AdornmentText) ? Adornment.Start : Adornment.None;
}

<ExpressionInput EditorContext="@EditorContext">
    <ChildContent>
        <MudTextFieldExtended
            T="string"
            Label="@Localizer[displayName]"
            Variant="Variant.Outlined"
            HelperText="@Localizer[description]"
            Margin="Margin.Dense"
            ReadOnly="EditorContext.IsReadOnly"
            Disabled="EditorContext.IsReadOnly"
            Value="@inputValue"
            ValueChanged="OnValueChanged">
            <AdornmentStart>
                @if (!string.IsNullOrWhiteSpace(_singleLineProps.AdornmentText))
                {
                    <MudText Color="Color.Info">@_singleLineProps.AdornmentText</MudText>
                }
            </AdornmentStart>
            <AdornmentEnd>
                @if (_singleLineProps.EnableCopyAdornment)
                {
                    <MudIconButton Icon="@Icons.Material.Filled.ContentCopy"
                                   OnClick="OnCopyClicked"
                                   Size="Size.Small"
                                   Class="mr-2"/>
                }
            </AdornmentEnd>
        </MudTextFieldExtended>
    </ChildContent>
</ExpressionInput>

@code {

    private SingleLineProps _singleLineProps = new();

    /// Gets or sets the editor context.
    [Parameter] public DisplayInputEditorContext EditorContext { get; set; } = null!;

    [Inject] private IClipboard Clipboard { get; set; } = null!;

    /// <inheritdoc />
    protected override void OnInitialized()
    {
        _singleLineProps = EditorContext.InputDescriptor.GetSingleLineProps();
    }

    private async Task OnValueChanged(string newValue)
    {
        await EditorContext.UpdateValueOrLiteralExpressionAsync(newValue.TrimWhitespace());
    }

    private async Task OnCopyClicked()
    {
        var value = (_singleLineProps.AdornmentText ?? string.Empty) + EditorContext.GetLiteralValueOrDefault();
        await Clipboard.CopyText(value);
    }

}